# coding=utf-8
__author__ = 'liubin'

import os
from flask import session, url_for, request
from flask.ext.admin import form
from flask.ext.restful import Resource, fields, marshal, reqparse
from project import api_view, Item, Order, OrderDetail, app, db


class CartListApi(Resource):
    """
    restful访问方式
    从session中获取购物车
    """

    #对于 cart的结构定义的restful映射对象
    _resource_fields = {
        'item_id': fields.String,
        'name': fields.String,
        'description': fields.String,
        'price': fields.Price(decimals=2),
        'count': fields.Integer,
        'image': fields.String,
        'store_id': fields.String,
        'store_name': fields.String
    }

    def get(self, **kwargs):
        """
        restful 的 get
        :param kwargs:
        :return:
        """
        data = []
        if u'items' in session:
            for order in session[u'items'].items():
                # session 默认以unicode处理
                item_id = order[0].encode()
                count = order[1]
                item = Item.query.filter_by(id=item_id).first()
                item_image = os.path.join(app.config['UPLOAD_DIRECTORY'], item.image).replace('\\', '/')
                data_cart = {
                    'item_id': item_id,
                    'name': item.name,
                    'price': item.price,
                    'description': item.description,
                    'count': count,
                    'image': url_for('static', filename=form.thumbgen_filename(item_image)),
                    'store_id': item.store_id,
                    'store_name': item.store.name
                }
                # marshal用来映射 restful 对象
                data.append(marshal(data_cart, self._resource_fields))
        #加上处理状态
        return {'success': True, 'data':data }

    def post(self, **kwargs):
        """
        restful 的 post
        购物车最终提交
        """

        # 请求参数的解析
        parser = reqparse.RequestParser()
        # !!必须要指定 location='args'
        parser.add_argument('customer', type=unicode, location='args', required=True)
        parser.add_argument('tel', type=unicode, location='args', required=True)
        parser.add_argument('comment', location='args', type=unicode)
        args = parser.parse_args()
        print(args)
        customer = args['customer']
        tel = args['tel']
        comment = args['comment']
        carts = request.get_json()
        # 订单提交
        #订单信息不为空
        if carts:
            # 建立订单头
            order = Order(customer=customer, tel=tel, comment=comment)
            db.session.add(order)
            amount = 0
            # 每行订单
            if isinstance(carts, list):
                # 多行订单
                for cart in carts:
                    print(cart)
                    print(cart['item_id'])
                    print(cart['count'])
                    count = cart['count']
                    item_id = cart['item_id']
                    order_detail = OrderDetail(count)
                    item = Item.query.filter_by(id = item_id).first()
                    order_detail.item = item
                    order_detail.order = order
                    db.session.add(order_detail)
                    amount = amount + item.price * count
            else:
                # 单行订单
                count = carts['count']
                item_id = carts['item_id']
                order_detail = OrderDetail(count)
                item = Item.query.filter_by(id = item_id).first()
                order_detail.item = item
                order_detail.order = order
                db.session.add(order_detail)
                amount = amount + item.price * count
            order.amount = amount
            db.session.commit()
            if u'items' in session:
                del session[u'items']
        return {'success': True}
class CartApi(Resource):
    """
    restful访问方式
    回改session的购物车
    """
    def put(self, item_id, **kwargs):
        """
        restful 的 post
        :param kwargs:
        :return:
        """

        # 请求参数的解析
        parser = reqparse.RequestParser()
        #parser.add_argument('item_id', type=int, required=True)
        parser.add_argument('count', type=int, required=True)
        args = parser.parse_args()
        #item_id = args['item_id']
        count = args['count']

        if not u'items' in session:
            session[u'items'] = {}
        if unicode(item_id) in session['items']:
            session[u'items'][unicode(item_id)] = count
        print(session)
        return {'success': True}

    def delete(self, item_id, **kwargs):
        if not u'items' in session:
            session[u'items'] = {}
        if unicode(item_id) in session['items']:
            del session[u'items'][unicode(item_id)]
        print(session)
        return {'success': True}


# 映射restful的url
api_view.add_resource(CartListApi, '/api/cart')
api_view.add_resource(CartApi, '/api/cart/<int:item_id>')